﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MKAdmin.ToolKit
{
    public static class ConfigHelper
    {
        #region
        /// <summary>
        /// 获取key的值（AppSetting）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T GetAppSetting<T>(this string key, T defaultValue = default(T))
        {
            if (string.IsNullOrWhiteSpace(key))
                return defaultValue;

            var value = ConfigurationManager.AppSettings[key] ?? string.Empty;

            if (string.IsNullOrWhiteSpace(value)) return defaultValue;

            if (defaultValue is bool)
                value = (value == "on").ToString();

            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// Key是否存在（AppSetting）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool KeyExist(this string key)
        {
            return ConfigurationManager.AppSettings.AllKeys.Any(k => k.Equals(key, StringComparison.CurrentCultureIgnoreCase));
        }

        /// <summary>
        /// 获取key的值（ConnectionString）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConnectionString(this string key)
        {
            if (string.IsNullOrWhiteSpace(key)) return string.Empty;

            var setting = ConfigurationManager.ConnectionStrings[key];

            return null != setting ? setting.ConnectionString : string.Empty;
        }
        #endregion
    }
}
